package display.scrollableWindow {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class Scrollbar extends MovieClip {
		
		//{ region Stage elements
		
		public var handle:MovieClip;
		public var scrollArea:MovieClip;
		
		//} endregion
		
		private const SCROLL_FACTOR:Number = 3;
		
		public function Scrollbar() {
			init();
		}
		
		private function init():void {
			handle.buttonMode = true;
			initListeners();
		}
		
		private function initListeners():void {
			handle.addEventListener(MouseEvent.MOUSE_DOWN, handle_MouseDown); 
		}
		
		public function setScrollPositionRatio(ratio:Number):void
		{
			var newY:Number = (scrollArea.height - handle.height) * ratio;
			if (newY < 0) 
				handle.y = 0;
			else if (newY > (scrollArea.height - handle.height)) 
				handle.y = scrollArea.height - handle.height;
			else
				handle.y = newY;
		}
		
		public function getScrollPositionRatio():Number {
			return (handle.y - scrollArea.y ) / scrollArea.height;
		}
		
		//{ region Handlers
		
		private function handle_MouseDown(event:MouseEvent):void {
			stage.addEventListener(MouseEvent.MOUSE_UP, stage_MouseUp);
			var area:Rectangle = new Rectangle(scrollArea.x, scrollArea.y, 0, scrollArea.height - handle.height);
			handle.startDrag(false, area);
			this.dispatchEvent(new Event(Event.SCROLL));
		}
		
		private function stage_MouseUp(event:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_UP, stage_MouseUp);
			handle.stopDrag();
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		//} endregion
		
		//{ region Public
		
		public function moveHandle(delta:int):void {
			var newY:Number = handle.y - delta * SCROLL_FACTOR;
			
			if (delta > 0) {
				if (newY > 0) {
					handle.y = newY;
				} else {
					handle.y = 0;
				}
			} 
			
			if (delta < 0) {
				if (newY < (scrollArea.height - handle.height)) {
					handle.y = newY;
				} else {
					handle.y = scrollArea.height - handle.height;
				}
			}
			
			/*if ((delta > 0 && handle.y < (scrollArea.height - handle.height)) || (delta < 0 && handle.y > 0)) {
				handle.y -= delta * SCROLL_FACTOR;
			}*/
		}
		
		//} endregion
		
	}

}